import request from '@/utils/request'
import type { ApiResponse, PaginationParams } from '@/types'
import type { PurchaseRequestItem } from '@/types/request'

/**
 * 获取求购信息列表
 * @param params 查询参数
 * @returns Promise<ApiResponse<{ content: PurchaseRequestItem[], totalElements: number }>>
 */
export async function getPurchaseRequests(params: any = {}): Promise<ApiResponse<{ content: PurchaseRequestItem[], totalElements: number }>> {
    // 从localStorage获取用户ID，用于处理收藏状态
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
        try {
            const parsedUserInfo = JSON.parse(userInfo);
            if (parsedUserInfo.id) {
                params.userId = parsedUserInfo.id;
            }
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    return request.get<ApiResponse<{ content: PurchaseRequestItem[], totalElements: number }>>('/requests', { params })
}

/**
 * 获取求购信息详情
 * @param id 求购信息ID
 * @returns Promise<ApiResponse<PurchaseRequestItem>>
 */
export async function getPurchaseRequestDetail(id: number | string): Promise<ApiResponse<PurchaseRequestItem>> {
    // 从localStorage获取用户ID，用于处理收藏状态
    const userInfo = localStorage.getItem('userInfo');
    let userId = null;

    if (userInfo) {
        try {
            const parsedUserInfo = JSON.parse(userInfo);
            userId = parsedUserInfo.id;
        } catch (error) {
            console.error('解析用户信息失败', error);
        }
    }

    const params = userId ? { userId } : {};
    return request.get<ApiResponse<PurchaseRequestItem>>(`/requests/${id}`, { params })
}

/**
 * 发布求购信息
 * @param data 求购信息数据
 * @returns Promise<ApiResponse<PurchaseRequestItem>>
 */
export async function createPurchaseRequest(data: any): Promise<ApiResponse<PurchaseRequestItem>> {
    return request.post<ApiResponse<PurchaseRequestItem>>('/requests', data)
}

/**
 * 更新求购信息
 * @param id 求购信息ID
 * @param data 更新数据
 * @returns Promise<ApiResponse<PurchaseRequestItem>>
 */
export async function updatePurchaseRequest(id: number | string, data: any): Promise<ApiResponse<PurchaseRequestItem>> {
    return request.put<ApiResponse<PurchaseRequestItem>>(`/requests/${id}`, data)
}

/**
 * 删除求购信息
 * @param id 求购信息ID
 * @returns Promise<ApiResponse<void>>
 */
export async function deletePurchaseRequest(id: number | string): Promise<ApiResponse<void>> {
    return request.delete<ApiResponse<void>>(`/requests/${id}`)
}

/**
 * 收藏求购信息
 * @param id 求购信息ID
 * @returns Promise<ApiResponse<{ favorited: boolean }>>
 */
export async function favoriteRequest(id: number | string): Promise<ApiResponse<{ favorited: boolean }>> {
    // 从localStorage获取用户信息
    const userInfo = localStorage.getItem('userInfo');
    const token = localStorage.getItem('token');

    if (!userInfo || !token) {
        throw new Error('用户未登录');
    }

    const parsedUserInfo = JSON.parse(userInfo);
    const userId = parsedUserInfo.id;

    if (!userId) {
        throw new Error('用户ID不存在');
    }

    return request.post<ApiResponse<{ favorited: boolean }>>(`/requests/${id}/favorite`,
        { userId },
        { headers: { 'Authorization': `Bearer ${token}` } }
    );
}

/**
 * 取消收藏求购信息
 * @param id 求购信息ID
 * @returns Promise<ApiResponse<{ favorited: boolean }>>
 */
export async function unfavoriteRequest(id: number | string): Promise<ApiResponse<{ favorited: boolean }>> {
    // 从localStorage获取用户信息
    const userInfo = localStorage.getItem('userInfo');
    const token = localStorage.getItem('token');

    if (!userInfo || !token) {
        throw new Error('用户未登录');
    }

    const parsedUserInfo = JSON.parse(userInfo);
    const userId = parsedUserInfo.id;

    if (!userId) {
        throw new Error('用户ID不存在');
    }

    return request.delete<ApiResponse<{ favorited: boolean }>>(
        `/requests/${id}/favorite?userId=${userId}`,
        { headers: { 'Authorization': `Bearer ${token}` } }
    );
}

/**
 * 检查求购信息是否已收藏
 * @param id 求购信息ID
 * @returns Promise<ApiResponse<{ favorited: boolean }>>
 */
export async function checkRequestFavorite(id: number | string): Promise<ApiResponse<{ favorited: boolean }>> {
    // 从localStorage获取用户信息
    const userInfo = localStorage.getItem('userInfo');
    const token = localStorage.getItem('token');

    if (!userInfo || !token) {
        throw new Error('用户未登录');
    }

    const parsedUserInfo = JSON.parse(userInfo);
    const userId = parsedUserInfo.id;

    if (!userId) {
        throw new Error('用户ID不存在');
    }

    return request.get<ApiResponse<{ favorited: boolean }>>(
        `/requests/${id}/favorite?userId=${userId}`,
        { headers: { 'Authorization': `Bearer ${token}` } }
    );
} 